<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Storage</title>
    <link rel="stylesheet" href="./style.css">
</head>

<body>
    <h1>Cookie </h1>
    <div id="app">
        <!-- 是否已经登录？Cookie? 检查 -->
        <section id="loginSection" style="display:none;">
            <form id="loginForm">
                <input type="text" id="username" placeholder="Username" required />
                <br/>
                <input type="password" id="password" placeholder="Password" required />
                <br/>
                <button type="submit">Login</button>
            </form>
        </section>

        <section id="welcomeSection" style="display:none;">
            <p>Welcome, <span id="userDisplay"></span></p>
            <button id="logoutBtn">Logout</button>
        </section>
        
    </div>
    <script>
        // console.log('智能前端，智能后端，笑傲秋招')
        const loginForm = document.getElementById('loginForm');
        loginForm.addEventListener('submit', async (event) => {
            event.preventDefault();
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();
            // console.log(username, password)
            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username,
                        password
                    })
                })
                const data = await response.json();
                // console.log(data);
            } catch (err) {
                console.log('登录出错了')
            }
        })

        document.addEventListener('DOMContentLoaded', async () => {
            // 登录吗？
            try {
                const response = await fetch('/check-login')
                const data = await response.json();
                console.log(data, '////||');
                if (data.loggedIn) {
                    document.getElementById('loginSection').style.display = 'none';
                    document.getElementById('welcomeSection').style.display = 'block';
                    document.getElementById('userDisplay').textContent = data.username;
                } else {
                    document.getElementById('loginSection').style.display = 'block';
                    document.getElementById('welcomeSection').style.display = 'none';
                }
            } catch (err) {

            }
        })
    </script>
</body>

</html>